/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.sprite.sheet;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import hapi.sprite.display.BitmapSpriteSheetDisplay;
import hapi.sprite.display.CacheBitmapDataSpriteSheetDisplay;
import hapi.sprite.display.SpriteSheetDisplay;

class CacheBitmapDataSpriteSheet extends SpriteSheetBase, implements DrawOnBitmapSpriteSheet {
	
	var sprites:IntHash<BitmapData>;
	
	public function new(source:BitmapData, width:Int, height:Int) {
		super(source, width, height);
		initSprites();
	}
	
	public inline function drawSpriteOn(canvas:Bitmap, spriteId:Int, dest:Point):Void {
		canvas.bitmapData = sprites.get(spriteId-1);
	}
	
	function initSprites() {
		this.sprites = new IntHash();
		var spriteBitmapData:BitmapData;
		var spriteRect = new Rectangle(0, 0, width, height);
		var destPoint = new Point(0.0, 0.0);
		var id = 0;
		for ( row in 0...rows ) {
			for ( col in 0...cols ) {
				spriteBitmapData = new BitmapData(width, height, true, 0x00000000);
				spriteRect.x = col * width;
				spriteRect.y = row * height;
				spriteBitmapData.copyPixels(source, spriteRect, destPoint);
				sprites.set(id, spriteBitmapData);
				++id;
			}
		}
	}
	
	public function createDisplay(?x:Float=0.0, ?y:Float=0.0):SpriteSheetDisplay {
		return createBitmapDisplay(x, y);
	}
	
	public function createBitmapDisplay(?x:Float = 0.0, ?y:Float = 0.0):BitmapSpriteSheetDisplay {
		return new CacheBitmapDataSpriteSheetDisplay(this, x, y);
	}
}